package com.boilerCloud.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * @create_time 2016年6月14日 上午2:02:52
 * @author lim
 * @description
 *
 */
public class QNFileUpload {
	private static Logger log = LoggerFactory.getLogger(QNFileUpload.class);

	// 设置好账号的ACCESS_KEY和SECRET_KEY
	private static String ACCESS_KEY = Configuration.readConfigString("qn_ak");
	private static String SECRET_KEY = Configuration.readConfigString("qn_sk");
	// 要上传的空间
	private static String bucketname = Configuration
			.readConfigString("qn_bucket");
	// 上传文件的路径

	// 密钥配置
	private static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	// 创建上传对象
	private static UploadManager uploadManager = new UploadManager();
	//上传路径
	private static String rootPath = Configuration.readConfigString("qn_url");

	// 简单上传，使用默认策略，只需要设置上传的空间名就可以了
	private static String getUpToken() {
		return auth.uploadToken(bucketname);
	}

/*	public static Response upload(String filePath, String remoteName)
			throws IOException {
		Response res =null;
		try {
			// 调用put方法上传
			 res=uploadManager.put(filePath, remoteName, getUpToken());
			// 打印返回的信息
			log.info(res.bodyString());
			return res;
		} catch (QiniuException e) {
			res = e.response;
			// 请求失败时打印的异常的信息
			log.error(res.toString());
			try {
				// 响应的文本信息
				log.error(res.bodyString());
			} catch (QiniuException e1) {
				// ignore
			}
			return res;
		}
	}*/
	
	
	
	public static String upload(String filePath, String remoteName) {
		String url ="";
		Response res = null;
		try {
			res=uploadManager.put(filePath, remoteName, getUpToken());
			if(res.isOK()){
				url = rootPath + JSON.parseObject(res.bodyString(),QnSuccess.class).getKey();
			}
		} catch (QiniuException e) {
			res = e.response;
			log.error(res.toString());// 请求失败时打印的异常的信息
			try {
				log.error(res.bodyString());// 响应的文本信息
			} catch (QiniuException e1) {
	
			}
		}
		
		return url;
		
	}
}

class QnSuccess {

	private String path;
	private String key;
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	
}